<template>
  <div class="min-h-screen bg-gray-900 text-white">
    <!-- 页面标题和返回按钮 -->
    <div class="fixed top-0 left-0 right-0 z-10 bg-gray-900 bg-opacity-90 backdrop-blur-sm">
      <div class="px-4 py-3 flex items-center justify-between border-b border-gray-700">
        <button @click="goBack" class="flex items-center text-blue-400 hover:text-blue-300">
          <span class="text-xl">←</span>
          <span class="ml-2">关闭页面</span>
        </button>
        <h1 class="text-xl font-bold">学生签到</h1>
        <div class="w-20"></div> <!-- 占位元素，保持标题居中 -->
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="pt-16 pb-8 px-4">
      <div class="max-w-4xl mx-auto">
        <!-- 签到设置 -->
        <div class="bg-gray-800 rounded-xl p-6 mb-6 shadow-lg" v-if="!isAttendanceStarted">
          <h2 class="text-2xl font-bold mb-4 text-center">签到设置</h2>
          
          <!-- 直播间标题设置 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-300 mb-2">直播间标题</label>
            <input 
              type="text" 
              v-model="liveName" 
              class="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入直播间标题"
            >
          </div>
          
          <!-- 签到时间设置 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-300 mb-2">签到时长（分钟）</label>
            <input 
              type="number" 
              v-model="attendanceDuration" 
              min="1" 
              max="120"
              class="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500"
              placeholder="请输入签到时长（1-120分钟）"
            >
          </div>
          
          <!-- 班级选择 -->
          <div class="mb-6">
            <label class="block text-sm font-medium text-gray-300 mb-2">选择班级</label>
            <!-- 如果有roomId，显示固定的班级信息 -->
            <div v-if="roomId" class="w-full px-4 py-2 bg-gray-600 border border-gray-500 rounded-lg text-white">
              房间ID: {{ roomId }}
            </div>
            <!-- 如果没有roomId，显示班级选择下拉框 -->
            <select 
              v-else
              v-model="selectedClass" 
              class="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white focus:outline-none focus:ring-2 focus:ring-blue-500"
            >
              <option value="" disabled>请选择班级</option>
              <option v-for="classItem in classList" :key="classItem.id" :value="classItem.id">
                {{ classItem.name }}
              </option>
            </select>
          </div>
          
          <!-- 开始签到按钮 -->
          <button 
            @click="startAttendance"
            :disabled="(!roomId && !selectedClass) || !attendanceDuration || !liveName.trim()"
            class="w-full bg-blue-600 hover:bg-blue-700 disabled:bg-gray-600 text-white font-medium py-3 px-4 rounded-lg transition-colors flex items-center justify-center gap-2"
          >
            <span>开始签到</span>
            <span>✅</span>
          </button>
        </div>

        <!-- 签到进行中 -->
        <div class="bg-gray-800 rounded-xl p-6 mb-6 shadow-lg text-center" v-else-if="isAttendanceStarted && countdown > 0">
          <h2 class="text-2xl font-bold mb-4">签到进行中</h2>
          <div class="text-5xl font-mono font-bold text-blue-400 mb-4">{{ formatTime }}</div>
          <div class="text-lg">班级: {{ getClassNameById(selectedClass) }}</div>
        </div>
        
        <!-- 签到结束 -->
        <div class="bg-gray-800 rounded-xl p-6 mb-6 shadow-lg text-center" v-else-if="isAttendanceStarted && countdown === 0">
          <h2 class="text-2xl font-bold mb-4 text-green-400">签到已结束</h2>
          <div class="text-5xl font-mono font-bold text-gray-400 mb-4">00:00</div>
          <div class="text-lg">班级: {{ getClassNameById(selectedClass) }}</div>
          <div class="mt-4 text-gray-300">签到时间已结束，感谢参与</div>
        </div>

        <!-- 签到统计 -->
        <div class="bg-gray-800 rounded-xl p-6 mb-6 shadow-lg" v-if="isAttendanceStarted">
          <h2 class="text-2xl font-bold mb-4 text-center">签到统计</h2>
          <div class="grid grid-cols-3 gap-4 text-center">
            <div class="bg-blue-900 bg-opacity-50 rounded-lg p-4">
              <div class="text-3xl font-bold">{{ signedUsers.length }}</div>
              <div class="text-blue-300">已签到</div>
            </div>
            <div class="bg-yellow-900 bg-opacity-50 rounded-lg p-4">
              <div class="text-3xl font-bold">{{ unseenUsers.length }}</div>
              <div class="text-yellow-300">未签到</div>
            </div>
            <div class="bg-green-900 bg-opacity-50 rounded-lg p-4">
              <div class="text-3xl font-bold">{{ totalCount }}</div>
              <div class="text-green-300">总人数</div>
            </div>
          </div>
        </div>

        <!-- 未签到人员 -->
        <div class="bg-gray-800 rounded-xl p-6 mb-6 shadow-lg" v-if="isAttendanceStarted">
          <h2 class="text-2xl font-bold mb-4">未签到人员</h2>
          <input 
            v-model="searchUnsigned" 
            placeholder="搜索未签到人员..." 
            class="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 mb-4"
          />
          <div class="space-y-3 max-h-64 overflow-y-auto pr-2">
            <div 
              v-for="user in filteredUnsignedUsers" 
              :key="user.id"
              class="p-4 rounded-lg flex items-center bg-red-900 bg-opacity-30"
            >
              <img :src="user.avatar" :alt="user.nickname" class="w-10 h-10 rounded-full mr-4">
              <div class="flex-1">
                <div class="font-medium">{{ user.nickname }}</div>
                <div class="text-sm text-gray-400">{{ user.department }}</div>
              </div>
              <div>
                <button 
                  @click="signUser(user.id)"
                  class="px-4 py-2 bg-green-600 hover:bg-green-700 rounded-lg transition-colors"
                >
                  标记签到
                </button>
              </div>
            </div>
          </div>
        </div>

        <!-- 已签到人员 -->
        <div class="bg-gray-800 rounded-xl p-6 shadow-lg" v-if="isAttendanceStarted">
          <h2 class="text-2xl font-bold mb-4">已签到人员</h2>
          <input 
            v-model="searchSigned" 
            placeholder="搜索已签到人员..." 
            class="w-full px-4 py-2 bg-gray-700 border border-gray-600 rounded-lg text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 mb-4"
          />
          <div class="space-y-3 max-h-64 overflow-y-auto pr-2">
            <div 
              v-for="user in filteredSignedUsers" 
              :key="user.id"
              class="p-4 rounded-lg flex items-center bg-green-900 bg-opacity-30"
            >
              <img :src="user.avatar" :alt="user.nickname" class="w-10 h-10 rounded-full mr-4">
              <div class="flex-1">
                <div class="font-medium">{{ user.nickname }}</div>
                <div class="text-sm text-gray-400">{{ user.department }}</div>
              </div>
              <div class="text-gray-300">
                签到时间: {{ user.time }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>

import { getAllClasses ,getAllStudents,getSignIn,updateSignIn} from '@/api/attendance';
import { io } from 'socket.io-client';
export default {
  name: 'Attendance',
  data() {
    return {
      isAttendanceStarted: false, // 签到是否已开始
      attendanceDuration: 2, // 签到时长（分钟）
      selectedClass: '', // 选择的班级
      countdown: 0, // 倒计时（秒）
      searchUnsigned: '',
      searchSigned: '',
      liveName: '', // 直播间标题
      liveTitle: '', // 从URL参数获取的直播间标题
      roomId: '', // 从URL参数获取的roomId
      // 班级列表
      classList: [],
      unseenUsers: [
        
      ],
      signedUsers: [
       
      ],
      timer: null,
      poller: null,
      signalingConnection: null,
      publishUrl: 'http://1.94.105.36:3000' // 默认信令服务器地址
    };
  },
  computed: {
    formatTime() {
      const minutes = Math.floor(this.countdown / 60);
      const seconds = this.countdown % 60;
      return `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
    },
    filteredUnsignedUsers() {
      return this.unseenUsers.filter(user =>
        (user.nickname || '').toLowerCase().includes(this.searchUnsigned.toLowerCase()) ||
        (user.department || '').toLowerCase().includes(this.searchUnsigned.toLowerCase())
      );
    },
    filteredSignedUsers() {
      return this.signedUsers.filter(user =>
        (user.nickname || '').toLowerCase().includes(this.searchSigned.toLowerCase()) ||
        (user.department || '').toLowerCase().includes(this.searchSigned.toLowerCase())
      );
    },
    totalCount() {
      return this.unseenUsers.length + this.signedUsers.length;
    }
  },
  methods: {
    async fetchClassList() {
      try {
        const response = await getAllClasses();
        console.log(response);
        if (response && response.data) {
          this.classList = response.data;
        } else {
          // 如果API没有返回预期的数据结构，使用默认数据
        }
      } catch (error) {
        console.error('获取班级列表失败:', error);
        // 出错时使用默认数据
        
      }
    },
    async startAttendance() {
      const classId = this.roomId || this.selectedClass;
      if (classId && this.attendanceDuration) {
        console.log(`开始签到，班级/房间: ${classId}, 持续时间: ${this.attendanceDuration} 分钟`);
        try {
          const response = await getAllStudents(classId, this.liveName);
          console.log('获取学生列表成功:', response);
          // 初始化未签到和已签到
          const allStudents = response.data || [];
          this.signedUsers = [];
          this.unseenUsers = allStudents.map(s => ({ ...s }));
        }catch (error) {
          console.error('获取学生列表失败:', error);
        }
        this.isAttendanceStarted = true;
        this.countdown = this.attendanceDuration * 60; // 转换为秒
        this.startTimer();
        this.startPollingSignIns();
        
        // 向信令服务器发送签到开始消息
        if (this.signalingConnection && this.signalingConnection.connected) {
          this.signalingConnection.emit('start-attendance', {
            roomId: classId,
            time: this.countdown,
            title: this.liveTitle
          });
          console.log('已向信令服务器发送签到开始消息, roomId:', classId);
        } else {
          console.warn('信令服务器未连接，无法发送签到开始消息');
        }
      }
    },
    startTimer() {
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--;
        } else {
          // 倒计时结束时停止定时器但保持签到状态
          clearInterval(this.timer);
          this.stopPollingSignIns();
        }
      }, 1000);
    },
    startPollingSignIns() {
      // 立即拉取一次
      this.fetchSignedUsers();
      // 每2秒轮询一次
      this.poller = setInterval(() => {
        this.fetchSignedUsers();
      }, 2000);
    },
    stopPollingSignIns() {
      if (this.poller) {
        clearInterval(this.poller);
        this.poller = null;
      }
    },
    async fetchSignedUsers() {
      const classId = this.roomId || this.selectedClass;
      if (!classId) return;
      try {
        const res = await getSignIn(classId, this.liveName);
        const signed = res.data || [];
        // 根据已签到列表更新本地状态
        const signedIds = new Set(signed.map(s => s.id));

        // 1) 从未签到中移除已签到
        const stillUnseen = [];
        for (const u of this.unseenUsers) {
          if (!signedIds.has(u.id)) {
            stillUnseen.push(u);
          }
        }
        this.unseenUsers = stillUnseen;

        // 2) 合并已签到（保持唯一）并更新签到时间
        const idToSigned = new Map(this.signedUsers.map(s => [s.id, s]));
        for (const s of signed) {
          const existing = idToSigned.get(s.id);
          if (existing) {
            existing.time = s.time || existing.time;
          } else {
            idToSigned.set(s.id, { ...s });
          }
        }
        this.signedUsers = Array.from(idToSigned.values());
      } catch (e) {
        console.error('获取已签到列表失败', e);
      }
    },
    getClassNameById(classId) {
      // 如果使用的是roomId，直接返回房间ID
      if (this.roomId && classId === this.roomId) {
        return `房间: ${this.roomId}`;
      }
      // 否则从班级列表中查找
      const classItem = this.classList.find(item => item.id === classId);
      return classItem ? classItem.name : '';
    },
    async signUser(userId) {
      // 本地先移除，提升交互速度
      const userIndex = this.unseenUsers.findIndex(user => user.id === userId);
      let user = null;
      if (userIndex !== -1) {
        user = this.unseenUsers.splice(userIndex, 1)[0];
        user.time = new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' });
        this.signedUsers.push(user);
      }
      try {
        await updateSignIn(userId, 1, this.liveName);
        // 与后端状态对齐，触发一次刷新
        await this.fetchSignedUsers();
      } catch (e) {
        console.error('标记签到失败', e);
        // 回滚本地状态
        if (user) {
          const idx = this.signedUsers.findIndex(u => u.id === user.id);
          if (idx !== -1) this.signedUsers.splice(idx, 1);
          this.unseenUsers.push(user);
        }
      }
    },
    goBack() {
      // 关闭当前标签页
      window.close();
    },
    connectSignalingServer() {
      try {
        // 连接Socket.IO服务器
        this.signalingConnection = io(this.publishUrl, {
          transports: ['websocket', 'polling'],
          reconnection: true,
          reconnectionAttempts: 5,
          reconnectionDelay: 1000,
          timeout: 10000 // 10秒连接超时
        });
        
        this.signalingConnection.on('connect', () => {
          console.log('已连接到信令服务器');
        });
        
        this.signalingConnection.on('disconnect', () => {
          console.log('与信令服务器断开连接');
        });
        
        this.signalingConnection.on('connect_error', (error) => {
          console.error('连接信令服务器失败:', error);
        });
      } catch (error) {
        console.error('初始化信令连接失败:', error);
      }
    }
  },
  async mounted() {
    // 解析URL参数获取roomId和liveTitle
    const urlParams = new URLSearchParams(window.location.search);
    const roomId = urlParams.get('roomId');
    const liveTitle = urlParams.get('liveTitle');
    
    if (roomId) {
      this.roomId = roomId;
      this.selectedClass = roomId; // 将roomId作为selectedClass使用
      console.log('从URL获取到roomId:', roomId);
    }
    
    if (liveTitle) {
      this.liveTitle = decodeURIComponent(liveTitle);
      this.liveName = this.liveTitle; // 将liveTitle作为liveName使用
      console.log('从URL获取到liveTitle:', this.liveTitle);
    }
    
    // 页面加载时获取班级列表
    await this.fetchClassList();
    
    // 连接Socket.IO服务器
    this.connectSignalingServer();
  },
  beforeUnmount() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    this.stopPollingSignIns();
    
    // 断开Socket.IO连接
    if (this.signalingConnection) {
      this.signalingConnection.disconnect();
      this.signalingConnection = null;
    }
  }
};
</script>

<style scoped>
/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: #374151;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: #6B7280;
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: #9CA3AF;
}
</style>